package com.zyk.leetcode;

import java.util.Arrays;

/**
 *
 * https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/
 *
 * @author zhangsan
 * @date 2021/4/4 23:24
 */
public class J45 {

    public static String minNumber(int[] nums) {
        String[] strs = new String[nums.length];
        for(int i = 0; i < nums.length; i++)
            strs[i] = String.valueOf(nums[i]);
        Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
        StringBuilder res = new StringBuilder();
        for(String s : strs)
            res.append(s);
        return res.toString();
    }

    public static String minNumber2(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            for (int j = i; j > 0 && (String.valueOf(nums[j])+ String.valueOf(nums[j-1])).compareTo(( String.valueOf(nums[j-1])+ String.valueOf(nums[j]))) < 0 ; j--) {
                swap(nums, j, j-1);
            }
        }
        StringBuilder res = new StringBuilder();
        for(int i : nums)
            res.append(i);
        return res.toString();
    }

    public static void swap(int[] arr, int a, int b) {
        arr[a] = arr[a] ^ arr[b];
        arr[b] = arr[a] ^ arr[b];
        arr[a] = arr[a] ^ arr[b];
    }

    // for test
    public static void main(String[] args) {
        int[] arr = {3,30,34,5,9};
        System.out.println(minNumber(arr));
        System.out.println(minNumber2(arr));
    }

}
